<?php
class UploadFileHandler
{
    private $db;
    private $vadFileAttr;
    private $operat;
    public function __construct(HuishengMysql $db)
    {
        $this->db = $db;
    }

    public function uploadFileHandle(VADFileAttr $vadFileAttr, AudioFileAllOperation $audioFileAllOperation)
    {
        try {
            $this->vadFileAttr = $vadFileAttr;
            $this->operat = $audioFileAllOperation;
            $this->aduioOperationCall($audioFileAllOperation);
            $this->modifyAudioData();
        } catch (\Exception $e) {
            file_put_contents("mysql.log",$e->getMessage());
            $this->updateFailLiveSpeech();
            var_dump($e->getMessage());
        }
    }

    private function aduioOperationCall()
    {
        $this->operat->moveFileandTrans2Wav($this->vadFileAttr->getOriginalPath(), $this->vadFileAttr->getVadPath());
        $this->operat->wavTrans2Another($this->vadFileAttr->getVadPath(), $this->vadFileAttr->getDestinationPath());
        $this->operat->wave2json($this->vadFileAttr->getVadPath(), $this->vadFileAttr->getDestinationJsonPath());
        $this->operat->vadWavFile($this->vadFileAttr->getVadPath());
    }

    private function modifyAudioData()
    {
        $vad_path = substr($this->vadFileAttr->getVadPath(), 0, -4);
        $this->insertVadSpeech($vad_path);
        $this->updateLiveSpeech();
    }

    private function insertVadSpeech($path)
    {
        $vadDatas = file("$path/test.lst");
        $return = array();
        foreach ($vadDatas as $key => $value) {
            $addr = trim(substr($value, 1));
            $time_arr = explode("_", trim(explode("/", trim($addr))[2]));
            $return[$key]['stime'] = $time_arr[0];
            $return[$key]['etime'] = $time_arr[1];
            $return[$key]['path'] = $path . "/" . pathinfo($addr)['filename'] . '.wav';
            $return[$key]['size'] = is_file($return[$key]['path']) ? floor(filesize($return[$key]['path']) / 1024) : 0;
            $return[$key]['sid'] = $this->vadFileAttr->getSpeechId();
            $return[$key]['sorting'] = $key;
            $return[$key]['create_time'] = $return[$key]['update_time'] = time();
        }
        $this->db->insertGrouptoVadSpeech($return);
    }

    private function updateLiveSpeech()
    {
        $seconds = $this->operat->waveDetailLength($this->vadFileAttr->getVadPath());
        $size = filesize($this->vadFileAttr->getDestinationPath());
        $insert_param = [
            "seconds" => $seconds,
            "size" => $size,
            "transition_state" => "1",
            "is_vad" => "1",
            "start_time" => time(),
            "update_time" => time()
        ];
        $this->db->updateDetailToLiveSpeech($insert_param, $this->vadFileAttr->getSpeechId());
    }

    private function updateFailLiveSpeech()
    {
        $this->db->updateMistaketoLiveSpeech($this->vadFileAttr->getSpeechId());
    }
}
